package com.slmxz.tms.core.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.slmxz.tms.common.component.RedisUserService;
import com.slmxz.tms.system.model.vo.UserInfoVO;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mybatis-plus 字段自动填充
 * @author sunyao
 * @Date 2024/10/28
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 新增填充创建时间
     *
     * @param metaObject 元数据
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime currentTime = LocalDateTime.now();
        this.setFieldValByName("createTime",currentTime,metaObject);
        this.setFieldValByName("updateTime",currentTime,metaObject);
        UserInfoVO userInfo = RedisUserService.currentUser();
        if(userInfo != null){
            Long userId = userInfo.getId();
            this.setFieldValByName("createBy",userId,metaObject);
            this.setFieldValByName("updateBy",userId,metaObject);
        }
    }

    /**
     * 更新填充更新时间
     *
     * @param metaObject 元数据
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        UserInfoVO userInfo = RedisUserService.currentUser();
        if(userInfo != null){
            Long userId = userInfo.getId();
            this.setFieldValByName("updateBy",userId,metaObject);
        }
        this.setFieldValByName("updateTime",LocalDateTime.now(),metaObject);
    }

}
